package ee.subjects.backend.model.dao.postgresqlimplementation;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import ee.subjects.backend.model.dao.ContactHibernateDAO;
import ee.subjects.backend.model.data.Contact;
import ee.subjects.backend.model.data.Contact_type;

public class ContactHibernateDAOPostgresImpl implements ContactHibernateDAO
{
	Session session;
	
	public ContactHibernateDAOPostgresImpl(Session hibernateSession)
	{
		this.session = hibernateSession;
	}
	
	@Override
	public void insertContact(Contact contact) 
	{
		session.save(contact);
	}

	@Override
	public Contact findContactById(int contactId) 
	{
		Contact contactReceived = (Contact) session.get(Contact.class, contactId);
		return contactReceived;
	}

	@Override
	public void updateContact(Contact updatedContactObject) 
	{
		session.update(updatedContactObject);
	}

	@Override
	public void deleteContactById(int contactId) 
	{
		Contact contactToDelete = (Contact) session.get(Contact.class, contactId);
		if (contactToDelete != null)
		{
			session.delete(contactToDelete);
		}
	}

	@Override
	public Contact_type getContact_typeById(int contact_typeId) 
	{
		Contact_type contact_type = null;
		try 
		{
			contact_type = (Contact_type) session.get(Contact_type.class, contact_typeId);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}	
		return contact_type;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> getAllSubjectContacts(int subjectId, int subject_typeId) 
	{
		List<Contact> listOfSubjectContacts = null;
		
		Query query = session.createQuery("from Contact where subject_fk = :subjectId and subject_type_fk = :subject_typeId");
		query.setInteger("subjectId", subjectId);
		query.setInteger("subject_typeId", subject_typeId);
		listOfSubjectContacts = (List<Contact>) query.list();
		return listOfSubjectContacts;
	}
}
